/*
 * @Author: 涵崽
 * @Date: 2023-12-25 10:05:53
 * @email: 1045654@qq.com
 * @gitee: https://gitee.com/han-zai
 * @LastEditors: 涵崽
 * @LastEditTime: 2024-02-29 16:19:20
 * @Description: 微信：1045654
 */
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import httpApi from '@/http'
import URLENV from '@/http/BaseUrl'
const URL = URLENV.URL
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '', // 新增
    roles: [] // 新增
  }
}

const state = getDefaultState()

const mutations = {
  // 新增
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  // 新增
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      httpApi.LoginApi.login({
        username: username.trim(),
        password: password
      })
        .then((res) => {
          localStorage.setItem('data', JSON.stringify(res.data.data))
          commit('SET_TOKEN', res.data.data.token)
          commit('SET_AVATAR', URL + res.data.data.avatar)
          commit('SET_NAME', '管理员')
          setToken(res.data.data.token) // token
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  async getInfo({ commit, state }) {
    try {
      const dataStr = localStorage.getItem('data')
      if (!dataStr) {
        // 处理数据不存在的情况
        return null // 或抛出错误，取决于你的需求
      }
      const data = JSON.parse(dataStr)
      commit('SET_ROLES', data.role)
      return data
    } catch (error) {
      // 处理JSON解析错误或其他错误
      console.error('Error fetching data from localStorage:', error)
      return null // 或抛出错误，取决于你的需求
    }
  },

  // user logout
  logout({ commit, state }) {
    removeToken()
    resetRouter()
    commit('SET_ROLES', [])
    localStorage.clear()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
